import axios from 'axios';
import { Message } from 'view-design';
import cookie from 'js-cookie';
import { LoadingBar } from 'view-design';

const baseUrl = `${window.location.protocol}//${process.env.NODE_ENV === 'production' ? 'mbookv2.lantingshucheng.com' : 'localhost:5000'}`;
axios.defaults.baseURL = baseUrl;
axios.defaults.timeout = 20000;

axios.interceptors.request.use(
  config => {
    const token = cookie.get('mbook-admin-token');
    if (token) config.headers.Authorization = token;
    return config;
  },
  err => Promise.reject(err)
);

axios.interceptors.response.use(
  response => Promise.resolve(response),
  error => Promise.resolve(error.response || error)
);

function checkStatus(response) {
  // 如果http状态码正常，则直接返回数据
  if (response && [200, 304, 400, 401, 403, 404, 500].indexOf(response.status) > -1) {
    return response;
  }
  // 异常状态(状态值不是以上的情况)下，把错误信息返回去
  return {
    ok: false,
    msg: '网络异常'
  };
}

function checkCode(res, options = {}) {
  if (res.status === 401) {
    Message.error('登录状态过期，请退出重新登录');
    window.location.href = 'index.html#/logout';
    return res;
  }
  if (res.status === 403) {
    window.location.href = 'index.html#/error-page/403';
    return res;
  }
  if (res.status === 404) {
    Message.error('接口地址不存在');
    return res;
  }

  if (res.status === 500) {
    Message.error('接口出错了');
    return res;
  }

  if (res.data && !res.data.ok && options.showMessage && res.data.msg !== 'validate-error') {
    if (res.data.msg) {
      Message.error(`${options.operation}失败, ${res.data.msg}`);
    } else {
      Message.error(`${options.operation}失败`);
    }
  }
  return res.data;
}

/**
 * 封装request请求，按业务场景定制功能
 */
const request = (options = {}) => {
  const newOptions = {
    method: 'GET',
    timeout: 50000,
    url: '',
    operation: '操作',
    showMessage: true,
    showGloabalLoading: false,
    ...options
  };
  if (!newOptions.params) {
    newOptions.params = {};
  }

  newOptions.showGloabalLoading && LoadingBar.start();
  return new Promise((resolve, reject) => {
    axios(newOptions)
      .then(response => {
        return checkStatus(response);
      })
      .then(response => {
        newOptions.showGloabalLoading && LoadingBar.finish();
        resolve(checkCode(response, newOptions));
      })
      .catch(err => {
        newOptions.showGloabalLoading && LoadingBar.finish();
        Message.error('网络异常');
        reject(err);
      });
  });
};

const oldHttp = {};
['get', 'post', 'put', 'delete', 'patch'].forEach(method => {
  oldHttp[method] = function(url, data, operation) {
    const params = method === 'get' ? data : {};
    return request({ method, url, params, data, operation });
  };
});

const baseURL = axios.defaults.baseURL;
export default request;
export { baseURL, oldHttp };
